package com.centaline.androidsalesblog.activities.newest;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.mine.FootPrintActivity;
import com.centaline.androidsalesblog.activities.search.NewEstateSearchActivity;
import com.centaline.androidsalesblog.api.newest.NewEstListApi;
import com.centaline.androidsalesblog.base.BaseFragment;
import com.centaline.androidsalesblog.base.BaseListMapActivity;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.CommonConstant;
import com.centaline.androidsalesblog.constants.DefaultHint;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.fragments.list.NewEstListFragment;
import com.centaline.androidsalesblog.fragments.listmap.NewPropListMapFragment;
import com.centaline.androidsalesblog.iml.DropCompleteListener;
import com.centaline.androidsalesblog.iml.RefreshListener;
import com.centaline.androidsalesblog.model.businissobject.DropBo;
import com.centaline.androidsalesblog.model.responseobject.NewEstListRo;
import com.centaline.androidsalesblog.rx.database.NewEstSearchDataFunc1;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.utils.DateUtil;
import com.centaline.androidsalesblog.utils.DropUtil;
import com.centaline.androidsalesblog.widgets.ListSearchView;
import com.centaline.androidsalesblog.widgets.dropdown.DoubleDrop;
import com.centaline.androidsalesblog.widgets.dropdown.MoreDrop;
import com.centaline.androidsalesblog.widgets.dropdown.SalePriceDrop;
import com.centaline.androidsalesblog.widgets.dropdown.SingleDrop;
import com.centanet.framework.interfaces.IResponseListener;
import com.trello.rxlifecycle.ActivityEvent;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func2;
import rx.functions.Func4;
import rx.schedulers.Schedulers;

/**
 * 新盘列表
 * Created by guilin on 16/2/23.
 */
public class NewEstListActivity extends BaseListMapActivity {

    private DoubleDrop doubleDrop;
    private SalePriceDrop salePriceDrop;
    private SingleDrop singleDrop;
    private MoreDrop moreDrop;

    private NewEstListFragment newEstListFragment;
    private NewPropListMapFragment newPropListMapFragment;

    private NewEstListApi newEstListApi;

    @Override
    protected void findViews() {
        super.findViews();
        setUniversalToolbar("新房");
    }

    @Override
    protected void initViews() {
        super.initViews();
        newEstListApi = new NewEstListApi(NewEstListActivity.class, NewEstListRo.class, new IResponseListener<NewEstListRo>() {
            @Override
            public void onResponse(NewEstListRo newEstListRo) {
                newEstListFragment.stopRefresh(newEstListRo.getNewEstDoArrayList());
                newPropListMapFragment.setMapArrayList(newEstListRo.getNewEstDoArrayList(), newEstListApi.getStartIndex() == 0);
                if (newEstListApi.getStartIndex() == 0) {
                    snack(newEstListRo.getTotal() == 0 ?
                            getString(R.string.snack_new_est_nothing) :
                            String.format(Locale.CHINA, getString(R.string.snack_new_est), newEstListRo.getTotal()));
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                newEstListFragment.refreshError();
                netWorkUnable();
            }
        });
        setFromSearch(getIntent(), false);
    }

    @Override
    protected boolean setShowFab() {
        return false;
    }

    @Override
    protected BaseFragment getFragment1() {
        newEstListFragment = new NewEstListFragment();
        newEstListFragment.setRefreshListener(new RefreshListener() {
            @Override
            public void down() {
                newEstListApi.setStartIndex(0);
                if (needLocation) {
                    startLocation();
                } else {
                    refreshList();
                }
            }

            @Override
            public void up(int count) {
                newEstListApi.setStartIndex(count);
                refreshList();
            }
        });
        return newEstListFragment;
    }

    @Override
    protected BaseFragment getFragment2() {
        newPropListMapFragment = new NewPropListMapFragment();
        return newPropListMapFragment;
    }

    @Override
    protected DefaultHint getDefaultHint() {
        return DefaultHint.NEWESTATE;
    }

    @Override
    protected ListSearchView.SearchCallback getSearchCallback() {
        return new ListSearchView.SearchCallback() {
            @Override
            public void clear() {
                newEstListApi.reset();
                resetTab(0);
                downRefresh(false);
            }

            @Override
            public void gotoSearch() {
                startActivityForResult(new Intent(NewEstListActivity.this, NewEstateSearchActivity.class),
                        CommonConstant.REQ_SEARCH);
                baiduEvent("D1_1_Click");
            }

            @Override
            public void gotoSearchVoice() {
                startActivityForResult(new Intent(NewEstListActivity.this, NewEstateSearchActivity.class)
                                .putExtra(ExtraConstant.SearchVoice, true),
                        CommonConstant.REQ_SEARCH);
                baiduEvent("D1_2_Click");
            }
        };
    }

    @Override
    protected void initDrop() {
        dropDownView.setDropCompleteListener(new DropCompleteListener() {
            @Override
            public void complete(int position, boolean fromMore, int type, DropBo... dropBos) {
                final int size = dropBos == null ? 0 : dropBos.length;
                if (fromMore) {
                    newEstListApi.resetOther();
                    if (size == 0) {
                        resetTab(3);
                        downRefresh(false);
                    } else {
                        setTab(3, "更多");
                        baiduEvent("D1_7_Value");
                        StringBuilder tags = new StringBuilder();
                        for (DropBo dropBo : dropBos) {
                            final int innerType = dropBo.getType();
                            switch (innerType) {
                                case 100://排序
                                    newEstListApi.setSortBy(dropBo.getValue());
                                    break;
                                case 40://户型
                                    if (dropBo.getValue() != null &&
                                            dropBo.getValue().contains(",")) {
                                        String[] rooms = dropBo.getValue().split(",");
                                        if (rooms[0].equals(rooms[1])) {
                                            newEstListApi.setRoomCnt(rooms[0]);
                                            newEstListApi.setGtRoomCnt("0");
                                        } else {
                                            newEstListApi.setRoomCnt(rooms[0]);
                                            newEstListApi.setGtRoomCnt("1");
                                        }
                                    }
                                    break;
                                case 130://开盘时间
                                    if (dropBo.getValue() != null &&
                                            dropBo.getValue().contains(",")) {
                                        String[] op = dropBo.getValue().split(",");
                                        Calendar calendar = Calendar.getInstance();
                                        calendar.setTime(new Date());
                                        int begin = Integer.parseInt(op[0]);
                                        int end = Integer.parseInt(op[1]);
                                        if (begin != 0) {
                                            calendar.add(Calendar.MONTH, begin);
                                        }
                                        newEstListApi.setOpDateBegin(DateUtil.format(begin == 0 ?
                                                        System.currentTimeMillis() : calendar.getTimeInMillis(),
                                                DateUtil.FORMAT2));
                                        if (end != 0) {
                                            calendar.add(Calendar.MONTH, end);
                                        }
                                        newEstListApi.setOpDateEnd(DateUtil.format(end == 0 ?
                                                        System.currentTimeMillis() : calendar.getTimeInMillis(),
                                                DateUtil.FORMAT2));
                                    }
                                    break;
                                case 80://特色
                                    tags.append(dropBo.getValue()).append(",");
                                    break;
                                default:
                                    break;
                            }
                        }
                        if (tags.toString().contains(",")) {
                            tags.deleteCharAt(tags.length() - 1);
                        }
                        newEstListApi.setTags(tags.toString());
                        downRefresh(false);
                    }
                } else {
                    switch (type) {
                        case 10://区域
                            newEstListApi.reset();
                            if (size == 1) {
                                if (DropUtil.compareValue(dropBos[0])) {
                                    resetTab(position);
                                } else {
                                    newEstListApi.setDistrictId(dropBos[0].getValue());
                                    setTab(position, dropBos[0].getText());
                                    baiduEvent("D1_4_Value", dropBos[0].getText());
                                }
                                downRefresh(false,true);
                            } else if (size == 2) {
                                newEstListApi.setDistrictId(dropBos[0].getValue());
                                if (DropUtil.compareValue(dropBos[1])) {
                                    setTab(position, dropBos[0].getText());
                                    baiduEvent("D1_4_Value", dropBos[0].getText());
                                } else {
                                    newEstListApi.setgScopeId(dropBos[1].getValue());
                                    setTab(position, dropBos[1].getText());
                                    baiduEvent("D1_4_Value", dropBos[1].getText());
                                }
                                downRefresh(false,true);
                            }
                            break;
                        case 11://附近
                            newEstListApi.reset();
                            if (size == 2) {
                                newEstListApi.setDistance(dropBos[1].getValue());
                                setTab(position, dropBos[1].getText());
                                baiduEvent("D1_4_Value", dropBos[1].getText());
                            }
                            downRefresh(true);
                            break;
                        case 30://均价
                            if (size == 1) {
                                String value = dropBos[0].getValue();
                                if (TextUtils.isEmpty(value)) {
                                    newEstListApi.setMinAveragePrice("");
                                    newEstListApi.setMaxAveragePrice("");
                                    resetTab(position);
                                    downRefresh(false);
                                } else if (value.contains(",")) {
                                    String[] values = value.split(",");
                                    newEstListApi.setMinAveragePrice(values[0]);
                                    newEstListApi.setMaxAveragePrice(values[1]);
                                    setTab(position, dropBos[0].getText());
                                    downRefresh(false);
                                    baiduEvent("D1_5_Value", dropBos[0].getText());
                                }
                            } else if (size == 2) {
                                newEstListApi.setMinAveragePrice(dropBos[0].getValue());
                                newEstListApi.setMaxAveragePrice(dropBos[1].getValue());
                                setTab(position, DropUtil.customPrice(dropBos[0], dropBos[1]));
                                downRefresh(false);
                                baiduEvent("D1_5_Value", DropUtil.customPrice(dropBos[0], dropBos[1]));
                            }
                            break;
                        case 110://物业类型
                            newEstListApi.setEstType("");
                            if (size == 1) {
                                if (TextUtils.isEmpty(dropBos[0].getValue()) ||
                                        "不限".equalsIgnoreCase(dropBos[0].getValue()) ||
                                        "全部".equalsIgnoreCase(dropBos[0].getValue())) {
                                    resetTab(position);
                                } else {
                                    newEstListApi.setEstType(dropBos[0].getValue());
                                    setTab(position, dropBos[0].getText());
                                    baiduEvent("D1_6_Value", dropBos[0].getText());
                                }
                            }
                            downRefresh(false);
                            break;
                        default:
                            break;
                    }
                }
            }
        });
        dropDownView.initTabs(R.array.newEst);
        doubleDrop = new DoubleDrop(dropDownView, this);
        salePriceDrop = new SalePriceDrop(dropDownView, this);
        singleDrop = new SingleDrop(dropDownView, this);
        moreDrop = new MoreDrop(dropDownView, this);
        dropDownView.addDrops(doubleDrop, salePriceDrop, singleDrop, moreDrop);

        Observable
                .combineLatest(RxDataBase
                                .getNewEstRegion()
                                .subscribeOn(Schedulers.io()),
                        RxDataBase.nearby(),
                        new Func2<ArrayList<DropBo>, DropBo, ArrayList<DropBo>>() {
                            @Override
                            public ArrayList<DropBo> call(ArrayList<DropBo> dropBos, DropBo dropBo) {
                                ArrayList<DropBo> temp = new ArrayList<>();
                                DropBo dropBo2 = new DropBo(10);
                                dropBo2.setText(CommonConstant.DROP_TEXT_NO_LIMITED);
                                dropBo2.setValue(CommonConstant.DROP_VALUE_NULL);
                                temp.add(dropBo2);
                                if (AppConstant.NearbyEnable) {
                                    temp.add(dropBo);
                                }
                                temp.addAll(dropBos);
                                return temp;
                            }
                        })
                .compose(this.<ArrayList<DropBo>>bindUntilEvent(ActivityEvent.DESTROY))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ArrayList<DropBo>>() {
                    @Override
                    public void call(ArrayList<DropBo> dropBos) {
                        doubleDrop.init(dropBos);
                    }
                });
        RxDataBase
                .getSearchData("NewHousePriceN")
                .map(new NewEstSearchDataFunc1(30))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<ArrayList<DropBo>>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<ArrayList<DropBo>>() {
                    @Override
                    public void call(ArrayList<DropBo> dropBos) {
                        salePriceDrop.init(dropBos);
                    }
                });
        RxDataBase
                .getSearchData("NewEstType")
                .map(new NewEstSearchDataFunc1(110))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<ArrayList<DropBo>>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<ArrayList<DropBo>>() {
                    @Override
                    public void call(ArrayList<DropBo> dropBos) {
                        singleDrop.init(dropBos);
                    }
                });

        Observable
                .combineLatest(
                        RxDataBase.getSearchData("NewPropOrderBy").map(new NewEstSearchDataFunc1(100)),
                        RxDataBase.getSearchData("Room").map(new NewEstSearchDataFunc1(40)),
                        RxDataBase.getSearchData("NewPropOpDate").map(new NewEstSearchDataFunc1(130)),
                        RxDataBase.getSearchData("NewPropFeatures").map(new NewEstSearchDataFunc1(80)),
                        new Func4<ArrayList<DropBo>, ArrayList<DropBo>, ArrayList<DropBo>, ArrayList<DropBo>, ArrayList<DropBo>>() {
                            @Override
                            public ArrayList<DropBo> call(ArrayList<DropBo> dropBos, ArrayList<DropBo> dropBos2, ArrayList<DropBo> dropBos3, ArrayList<DropBo> dropBos4) {
                                final ArrayList<DropBo> list = new ArrayList<>();
                                DropBo dropBo;
                                if (dropBos.size() > 0) {
                                    dropBo = new DropBo(100);
                                    dropBo.setText("排序");
                                    dropBo.setValue(CommonConstant.DROP_VALUE_NULL);
                                    dropBo.setChildrenList(dropBos);
                                    list.add(dropBo);
                                }
                                if (dropBos2.size() > 0) {
                                    dropBo = new DropBo(40);
                                    dropBo.setText("房型");
                                    dropBo.setValue(CommonConstant.DROP_VALUE_NULL);
                                    dropBo.setChildrenList(dropBos2);
                                    list.add(dropBo);
                                }
                                if (dropBos3.size() > 0) {
                                    dropBo = new DropBo(130);
                                    dropBo.setText("开盘时间");
                                    dropBo.setValue(CommonConstant.DROP_VALUE_NULL);
                                    dropBo.setChildrenList(dropBos3);
                                    list.add(dropBo);
                                }
                                if (dropBos2.size() > 0) {
                                    dropBo = new DropBo(80);
                                    dropBo.setText("特色");
                                    dropBo.setSelected(true);
                                    dropBo.setValue(CommonConstant.DROP_VALUE_NULL);
                                    dropBo.setChildrenList(dropBos4);
                                    list.add(dropBo);
                                }
                                return list;
                            }
                        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<ArrayList<DropBo>>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<ArrayList<DropBo>>() {
                    @Override
                    public void call(ArrayList<DropBo> dropBos) {
                        moreDrop.init(dropBos);
                    }
                });
    }


    @Override
    protected void downRefresh(boolean needLocation, boolean clearLocation) {
        this.needLocation = needLocation;
        if (clearLocation) {
            newEstListFragment.setLocation(null);
        }
        newEstListFragment.startRefresh();
    }


    @Override
    protected void locationInfo(BDLocation bdLocation) {
        switch (bdLocation.getLocType()) {
            case 61:
            case 161:
                LatLng latLng = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
                newEstListFragment.setLocation(latLng);
                newEstListApi.setLatLng(latLng);
                refreshList();
                break;
            default:
                newEstListFragment.setLocation(null);
                newEstListApi.setLatLng(null);
                break;
        }
    }

    private void refreshList() {
        newEstListApi.startRequest();
    }

    private void resetTab(int position) {
        dropDownView.resetTab(position);
    }

    private void setTab(int position, String tab) {
        dropDownView.setTab(position, tab);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fab:
                startActivity(new Intent(this, FootPrintActivity.class));
                break;
            default:
                break;
        }
    }

    protected void setFromSearch(Intent intent, boolean request) {
        if (intent != null) {
            String query = intent.getStringExtra(ExtraConstant.SearchContent);
            if (!TextUtils.isEmpty(query)) {
                setSearchContent(query);
                newEstListApi.reset();
                newEstListApi.setTitle(query);
            }
            if (request) {
                downRefresh(false);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            switch (requestCode) {
                case CommonConstant.REQ_SEARCH:
                    setFromSearch(data, true);
                    break;
                default:
                    break;
            }
        }
    }
}
